﻿
using System.Collections;
using System.Collections.Generic;
using Xceed.Words.NET;

namespace FiveMonth.FormWork.Word
{
    internal class Element
    {
        public Element(DocXElement real, Element parent)
        {
            this.Real = real;
            this.Parent = parent;
            if (this.Parent != null)
            {
                this.Level = parent.Level + 1;
            }
            else
            {
                this.Level = 0;
            }
        }

        public int Level { get; set; }
        public Element Parent { get; set; }
        public DocXElement Real { get; set; }
        public Element GetParent(int level)
        {
            if (level < 1 || level >= this.Level)
            {
                return null;
            }

            var e = this;
            while (true)
            {
                e = e.Parent;
                if (e == null)
                {
                    return null;
                }
                if (e.Level == level)
                {
                    return e;
                }
            }
        }

        public string ParagraphText()
        {
            return As<Paragraph>()?.Text;
        }

        public T As<T>() where T : DocXElement
        {
            return Real as T;
        }

        public IList<Element> Children { get; set; }

        public override string ToString()
        {
            var str = this.Parent?.ToString() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(str))
            {
                str = str + " ";
            }

            str += string.Format("({0})", Real.GetType().Name);
            return str;
        }
    }
}